package com.gufe.controller.user.mp.quiz;

import com.gufe.dto.quiz.QuestionDTO;
import com.gufe.dto.quiz.SubmitPointsDTO;
import com.gufe.result.Result;
import com.gufe.service.user.mp.quiz.QuizService;
import com.gufe.utils.JwtUtil;
import com.gufe.vo.quiz.ResultVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController @RequestMapping("/api/quiz")
public class QuizController {

    @Autowired
    private QuizService quizService;

    @Value("${zbt.jwt.user-secret-key}")
    private String jwtSecret;

    @GetMapping("/questions/{competitionId}")
    public Result<List<QuestionDTO>> getQuestions(@PathVariable Long competitionId,@RequestHeader(HttpHeaders.AUTHORIZATION) String authorizationHeader) {

        String userId = extractUserIdFromToken(authorizationHeader);
        if (userId == null) {
            return Result.error("未授权"); // 未授权
        }
        return Result.success(quizService.getQuestionsByCompetitionId(competitionId));
    }

    @PostMapping("/submit/{competitionId}")
    public Result<ResultVO> submitQuiz( @RequestBody SubmitPointsDTO points, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorizationHeader) {
        // 从请求头中获取 token 并校验用户
        String Id = extractUserIdFromToken(authorizationHeader);
        if (Id == null) {
            return Result.error("未授权"); // 未授权
        }
        long userId;
        if (Id != null) {
            userId = Long.parseLong(Id);
        } else {
            System.err.println("错误：userId 头部为空或不存在");
            userId = -1; // 或者其他合适的默认值
        }
        return Result.success(quizService.submitPoints(points));
    }

    private String extractUserIdFromToken(String authorizationHeader) {
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            try {
                Claims claims = JwtUtil.parseJWT(jwtSecret, token);
                Object userIdObject = claims.get("userId"); // 获取到的可能是 Integer 或 String

                if (userIdObject instanceof Integer) {
                    return String.valueOf(userIdObject); // 如果是 Integer，转换为 String
                } else if (userIdObject instanceof String) {
                    return (String) userIdObject;      // 如果是 String，直接返回
                } else {
                    // 处理其他意外类型，例如返回 null 或抛出异常
                    System.err.println("userId Claim 类型不正确: " + (userIdObject != null ? userIdObject.getClass().getName() : "null"));
                    return null;
                }
            } catch (Exception e) {
                System.err.println("Token解析失败: " + e.getMessage());
                return null;
            }
        }
        return null;
    }

}